﻿using AutoMapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using WMS.Seven.Models;
using WMS.Seven.ProductSaleDetils.Dto;
using static Volo.Abp.Identity.Settings.IdentitySettingNames;

namespace WMS.Seven.ProductSaleDetils
{

    public class ProductSaleDetilsAppService: ApplicationService, IProductSaleDetilsAppService
    {
        private readonly IRepository<Products, int> _ProductsRepository;
        private readonly IRepository<Sales,int> _SalesRepository;
        private readonly IRepository<SaleDetils, int> _SaleDetailsRepository;

        private readonly IMapper _mapper; // 依赖注入 IMapper

        public ProductSaleDetilsAppService(IRepository<Products, int> ProductsRepository, IRepository<Sales, int> salesRepository, IRepository<SaleDetils, int> saleDetailsRepository, IMapper mapper)
        {
            _ProductsRepository = ProductsRepository;
            _SalesRepository = salesRepository;
            _SaleDetailsRepository = saleDetailsRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 商品信息
        /// </summary>
        /// <returns></returns>

        public async Task<string> SelectProduct()
        {
            var list= await _ProductsRepository.ToListAsync();
            var user = ObjectMapper.Map<List<Products>, List<ProductDto>>(list);
            return JsonConvert.SerializeObject(new PageDto<ProductDto>
            {
                code = "",
                data = user,
                msg = "",
                count = user.Count
            });
        }


        /// <summary>
        /// 添加商品销售信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        
        public async Task<object> AddProductSaleis(ProductSalesDto input)
        {
            //using (var transaction = await _SalesRepository.BeginTransactionAsync())
            //{
            //    try
            //    {
            //        // 可能在这里增加对 input 的验证
            //        if (input == null)
            //        {
            //            throw new ArgumentException("输入参数不可为 null", nameof(input));
            //        }

            //        var result = await CreateSalesAndDetails(input);
            //        await transaction.CommitAsync();
            //        return result;
            //    }
            //    catch (Exception ex)
            //    {
            //        await transaction.RollbackAsync();
            //        // 记录异常信息
            //        Console.WriteLine($"发生错误: {ex.Message}");
            //        // 可以考虑记录更详细的异常，比如 ex.StackTrace
            //        throw; // 保持重新抛出异常，以便外部调用者处理
            //    }
            //}



            var result = await CreateSalesAndDetails(input);
            return result;
        }

        private async Task<int> CreateSalesAndDetails(ProductSalesDto input)
        {
      

            var sales = new Sales
            {
                SalesOrderCode = input.SalesOrderCode,
                OutQuantity = input.Quantity,
                ReturnQuantity = input.ReturnQuantity,
                ReturnOutQuantity = input.ReturnOutQuantity,
                CreateTime = input.CreateTime,
                Maker = input.Maker,
                MakeTime = input.MakeTime,
                Remark = input.Remark,
                DeliveryDate = input.DeliveryDate,
                CustomerCode = input.CustomerCode,
                CustomerName = input.CustomerName,
                CustomerContact = input.CustomerContact,
                CustomerPhone = input.CustomerPhone,

   


            };

            await _SalesRepository.InsertAsync(sales);

            var detail = new SaleDetils
            {
                Quantity= input.Quantity,
                ProductCode = input.ProductCode,
                SalesOrderCode = input.SalesOrderCode,
               
            };

            await _SaleDetailsRepository.InsertAsync(detail);

            return 1; // 返回值可以根据业务逻辑调整
        }

        /// <summary>
        /// 获取销售订单详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<PSDelitDto>> SelectFormProductSale(string SalesOrderCode, string ProductCode, string ProductName, int pageIndex, int pageSize)
        {
            var saleDetails = await _SaleDetailsRepository.GetQueryableAsync();
            var sales = await _SalesRepository.GetQueryableAsync();
            var products = await _ProductsRepository.GetQueryableAsync();
            var query = from a in saleDetails
                        join b in sales on a.SalesOrderCode equals b.SalesOrderCode
                        join c in products on a.ProductCode equals c.ProductCode
                        select new PSDelitDto // 假设 PSDelitDto 是目标对象类型
                        {
                            // 数量
                            Quantity = a.Quantity,
                            // 产品编码（长度：40）
                            ProductCode = a.ProductCode,
                            // 产品名称
                            ProductName = c.ProductName,
                            // 订单编号
                            SalesOrderCode = a.SalesOrderCode,
                            // 总额
                            SumPrice = a.Quantity * c.UnitPrice,
                            // 产品规格
                            ProductSpecification = c.ProductSpecification,
                            // 单位
                            Unit = c.Unit,
                            // 单位价格
                            UnitPrice = c.UnitPrice,
                            // 客户编号
                            CustomerCode = b.CustomerCode,
                            // 客户名称
                            CustomerName = b.CustomerName,
                            // 客户联系方式
                            CustomerContact = b.CustomerContact,
                            // 客户电话
                            CustomerPhone = b.CustomerPhone,
                            // 退货
                            ReturnQuantity = b.ReturnQuantity,
                            // 退货数量
                            ReturnOutQuantity = b.ReturnOutQuantity,
                            OutQuantity = b.OutQuantity,
                     
                            CreateTime = b.CreateTime,
                        };

            query = query.WhereIf(!string.IsNullOrEmpty(SalesOrderCode), m => m.SalesOrderCode == SalesOrderCode);
            query = query.WhereIf(!string.IsNullOrEmpty(ProductCode), m => m.ProductCode == ProductCode);
            query = query.WhereIf(!string.IsNullOrEmpty(ProductName), m => m.ProductName.Contains(ProductName));

            // 添加分页
          
             query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return  query.ToList(); // 使用 ToListAsync() 进行异步操作
        }


        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="SalesOrderCode"></param>
        /// <returns></returns>
        public async Task<int> DeleteProduSaleDetils(string SalesOrderCode)
        {
            var DeleteSaleDetils =  _SaleDetailsRepository.DeleteAsync(m => m.SalesOrderCode == SalesOrderCode);
            var DeleteSales = _SalesRepository.DeleteAsync(m => m.SalesOrderCode == SalesOrderCode);

            return 1;
        }


        public async Task<Sales> FillSaleDetailsAsync(string SalesOrderCode)
        {
            // 查找销售记录
            var Saleit=await _SalesRepository.GetAsync(m => m.SalesOrderCode == SalesOrderCode);
            return Saleit;
        }


        // 假设这个方法用于获取与销售相关的产品 ID 列表
        public async Task<string> GetProductIdsBySaleIdAsync(string ProductCode)
        {
            // 假设根据ProductCode获取与销售相关的产品ID列表
            var products = await _ProductsRepository.ToListAsync();
            if (!string.IsNullOrEmpty(ProductCode))
            {
                products = products.Where(x => x.ProductCode == ProductCode).ToList();
            }
            var user = ObjectMapper.Map<List<Products>, List<ProductDto>>(products);
            return JsonConvert.SerializeObject(new PageDto<ProductDto>
            {
                code = "",
                data = user,
                msg = "",
                count = user.Count
            });

        }









    }
}
